﻿/// <reference path="jquery.intellisense.js"/>
/// <reference path="common.js" />
var formchanged = false;

$(function() {
    //if closeaftersave defined - close form
    if ($('#postback').length > 0) {
        try { if (afterSave) { afterSave(); } } catch (e) { }
        if ($('#closeaftersave').val() == 'true') self.close();
    }

    //validate form first time to initialize validator
    $('.validate').validate({ ignore: '.ignore' });
    $('.validate input').keydown(function(e) { if (e.keyCode == 13) { formchanged = true; return false; } });
    //$('textarea').keydown(function(e) { if (e.keyCode == 27) { return false; } });

    if ($.browser.msie && parseInt($.browser.version.substr(0, 1), 10) < 8) { $('label.required').append('<span class="red">*</span>'); }

    $('input,textarea,select').change(function() { formchanged = true; });
    $('input:text:visible:first:enabled:not(.dateTimeRU)').focus();

    $(document).bind('keydown', 'Ctrl+s', function() { $('.save').trigger('click'); return false; }).bind('keypress', 'Ctrl+s', function() { $('.save').trigger('click'); return false; });
    $(document).bind('keydown', 'Ctrl+Shift+s', function() { $('.saveandreturn').trigger('click'); return false; }).bind('keypress', 'Ctrl+Shift+s', function() { $('.saveandreturn').trigger('click'); return false; });
    $(document).bind('keydown', 'Esc', function() { $('.return').trigger('click'); return false; }).bind('keypress', 'Esc', function() { $('.return').trigger('click'); return false; });

    if ($('#tab').val()) setTab($('#tab').val());
});

function findTab(field)
{
    var prt = field.parentNode;
    while(prt != null)
    {
        if( $(prt).hasClass('tab') ) return prt.id;
        else prt = prt.parentNode;
    }
}

function closeForm(url) {
    if (formchanged == true && (!$('#readonly') || $('#readonly').val() != 'true') && !confirm('Форма была изменена. Вы уверены, что хотите выйти?')) return;
    if (url == 'close') {
        self.close();
        return;
    }
    
    if (url) {
        document.location.href =  (url == 'about:blank') ? url : base + url;
        return;
    }
    
    var f = $('form:first');
    var action = f.attr('action');
    var controller = action.substr(0, action.indexOf('/'));
    document.location.href = base + controller + '/list';
}